# -*- coding:utf-8 -*-
import time, os
import tkinter.filedialog
import tkinter.font
from tkinter import *
from tkinter import ttk
from db import get_by_type, update, close, get_last_18, get_last_1
import threading  # 多线程
from cv2 import cv2
# from tkinter import filedialog  # 文件控件
from PIL import Image, ImageTk  # 图像控件
from player import Player
from item import MyDialog
# from edit import ItemEdit
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
# faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')


class App(Tk):
    def __init__(self):
        super().__init__()
        self.title('RF领用超简易版 Version 0.00.07 Copyright © 2019 贾维程. All rights reserved.')
        self.minsize(1024, 768)
        self.now_label_string = StringVar()  # 时间字符串
        self.tel = StringVar()  # 输入框文本
        self.input = None  # 输入框
        self.canvas: Canvas  # 画布,显示摄像头
        self.image_file = None    # 画布中的图片需要全局引用
        self.capture = cv2.VideoCapture(0)
        self.style = ttk.Style()
        self.item_dict = {}  # 所有Label字典
        self.previous = {}  # 上一次处理的项目
        self.task_scheduler = BackgroundScheduler()
        self.frame_bottom: ttk.LabelFrame
        self.setup_UI()
        self.update_clock()
        self.cap()
        self.player = Player()
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.mainloop()

    def setup_UI(self):
        self.wm_state('zoomed')
        big_font = tkinter.font.Font(size=60)
        # small_font = tkinter.font.Font(size=12)
        frame_top = ttk.LabelFrame(self)
        frame_top.pack(side=TOP, fill=X)

        frame_top_left = ttk.Frame(frame_top)
        # frame_top_left["relief"] = "solid"
        self.input = ttk.Entry(frame_top_left, textvariable=self.tel, font=big_font)
        self.input.pack(side=TOP, padx=5, pady=5)
        self.input.focus_set()
        self.input.bind('<Return>', self.borrow)
        ttk.Label(frame_top_left, textvariable=self.now_label_string, font=big_font, anchor=CENTER).pack(side=TOP, padx=5, pady=5)
        frame_top_left.pack(side=LEFT, expand=YES)

        frame_top_right = ttk.Frame(frame_top)
        frame_top_right["relief"] = "solid"
        self.canvas = Canvas(frame_top_right, bg='#c4c2c2', height=240, width=320)  # 绘制画布
        self.canvas.pack()
        frame_top_right.pack(side=RIGHT)

        self.style.configure("red.TLabel", background="red", width=10)
        self.style.configure("green.TLabel", background="green", width=10)
        for i in range(1, 4):
            if i == 1:
                title = 'RF枪'
            elif i == 2:
                title = 'PDA'
            else:
                title = '蓝牙打印机'
            frame_main = ttk.LabelFrame(self, text=title)
            for index, item in enumerate(get_by_type(i)):
                status = get_last_1(item[0])
                button = ttk.Label(frame_main, text=item[0] + '\n' + item[1], style='red.TLabel' if (status and status[0] == '领用') else 'green.TLabel')
                button.bind('<Button-1>', self.item_click)
                # button.bind('<Button-3>', self.item_right_click)
                button.grid(row=index // 18, column=index % 18, padx=3, pady=3)
                self.item_dict[item[0]] = button
            frame_main.pack(side=TOP, fill=BOTH)
        self.frame_bottom = ttk.LabelFrame(self, text='流水记录')
        self.update_bottom_frame()
        self.frame_bottom.pack(side=BOTTOM, fill=X)
        if not os.path.exists('图片'):
            os.mkdir('图片')
        # 每天3点运行 图片清理程序
        self.task_scheduler.add_job(self.clear_old_img, CronTrigger(hour='3'))
        self.task_scheduler.start()

    def update_clock(self):
        # 更新时间 每秒调用一次
        self.now_label_string.set(time.strftime("%Y{}%m{}%d{} %H:%M:%S", time.localtime()).format('年', '月', '日'))
        self.after(1000, self.update_clock)

    def update_bottom_frame(self):
        for widget in self.frame_bottom.winfo_children():
            widget.destroy()
        for index, item in enumerate(get_last_18()):
            button = ttk.Label(self.frame_bottom, text=item[0] + '\n' + item[1],
                               style='green.TLabel' if item[2] == '归还' else 'red.TLabel')
            button.bind('<Button-1>', self.item_click)
            # button.grid(row=index // 18, column=index % 18, padx=3, pady=3)
            button.pack(side=LEFT, padx=3, pady=3)

    def cap(self):
        if self.capture.isOpened():
            ret, frame = self.capture.read()  # 从摄像头读取照片
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            # faces = faceCascade.detectMultiScale(
            #     gray,
            #     scaleFactor=1.2,
            #     minNeighbors=5,
            #     minSize=(20, 20)
            # )
            #
            # for (x, y, w, h) in faces:
            #     cv2.rectangle(gray, (x, y), (x + w, y + h), (0, 0, 255), 2)

            img = Image.fromarray(gray)
            out = img.resize((320, 240), Image.ANTIALIAS)
            self.image_file = ImageTk.PhotoImage(out)
            self.canvas.delete('all')
            self.canvas.create_image(0, 0, anchor='nw', image=self.image_file)
        # 更新摄像头 每40毫秒调用一次 相当于每秒25帧
        self.after(40, self.cap)

    def close(self):
        # 退出释放摄像头
        self.capture.release()
        close()
        self.destroy()

    def borrow(self, event):
        # 领用 or 归还
        rf_id = self.tel.get()
        self.tel.set('')
        ct = time.time()
        if rf_id in self.previous and ct - self.previous[rf_id] < 1:
            return
        if rf_id not in self.item_dict:
            threading.Thread(target=self.player.play, args=('编号错误',)).start()
        else:
            self.previous = {rf_id: ct}
            rfdate, rftime = self.now_label_string.get().split(' ')
            name = self.item_dict[rf_id]['text'].split('\n')[-1]
            data_secs = (ct - int(ct)) * 1000
            rfbmp = f'图片/{rf_id} {name} {time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()) + " " + str(data_secs)}.jpg'
            if self.capture.isOpened():
                ret, frame = self.capture.read()  # 从摄像头读取照片
                cv2.imencode(".jpg", frame)[1].tofile(rfbmp)
            if self.item_dict[rf_id]['style'] == 'red.TLabel':
                update(rf_id, name, '归还', rfdate, rftime, rfbmp)
                self.item_dict[rf_id]['style'] = 'green.TLabel'
                threading.Thread(target=self.player.play, args=('成功归还',)).start()
            else:
                update(rf_id, name, '领用', rfdate, rftime, rfbmp)
                self.item_dict[rf_id]['style'] = 'red.TLabel'
                threading.Thread(target=self.player.play, args=('领用成功',)).start()
            self.update_bottom_frame()

    def item_click(self, event):
        # 点击查询领用记录
        rfid = event.widget['text'].split('\n')[0]
        select_dialog = MyDialog(rfid)
        self.wait_window(select_dialog)
        self.input.focus_set()

    def clear_old_img(self):
        for file in os.listdir('图片'):  # 不仅仅是文件，当前目录下的文件夹也会被认为遍历到
            if time.time() - os.path.getctime('图片/' + file) > 30 * 24 * 3600:
                os.remove('图片/' + file)

    # def item_right_click(self, event):
    #     rfid, raname = event.widget['text'].split('\n')
    #     right_menu = Menu(self, tearoff=False)
    #     right_menu.add_command(label='修改')
    #     right_menu.add_command(label='删除')
    #     right_menu.post(event.x_root,event.y_root)


if __name__ == '__main__':
    app = App()
    # pyinstaller -F -w -i Snow_leopard_animal_72px_505797_easyicon.net.ico main.py
